import { createRouter, createWebHistory } from 'vue-router';
import routes from './modules';
import { isEmpty, isNotUndefined } from '../commons/utils';
import { hasMenuPermission } from './forward';
import storage from '@/commons/storage';
import constants from '@/commons/constants';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({ showSpinner: false });

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    if (to.path === from.path) return;
    NProgress.start();
    if (isNotUndefined(to?.meta?.loginAuth) && !to?.meta?.loginAuth) {
        next();
    } else if (!storage.has('ZW-TOKEN')) {
        next({ path: '/login', replace: true });
    } else if (constants.BLUE_ROUTE_LIST.includes(to.path)) {
        next();
        //TODO 如果切换到不同模块下，这里需要扩展code
    } else if (isEmpty(storage.get('ZW-TENANT-ID'))) {
        next({ path: '/company', replace: true });
    } else if (isEmpty(storage.get('ZW-AUTH'))) {
        next({ path: '/home', replace: true });
    } else {
        hasMenuPermission(next, to.path);
    }
});
router.afterEach(() => {
    NProgress.done();
});
export { router };
